package com.qf.fengmimall.index.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fengmimall.dto.CategoryProductDto;
import com.qf.fengmimall.index.entity.Category;
import com.qf.fengmimall.product.entity.Product;
import com.qf.fengmimall.index.mapper.CategoryMapper;
import com.qf.fengmimall.product.mapper.ProductMapper;
import com.qf.fengmimall.index.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author lx
 * @since 2023-02-13
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ProductMapper productMapper;

    /**
     * 分级
     *
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> getCategorys() {
        //产需所有分类商品
        List<Category> categories = list();
        List<Category> categoryList = getCategories(categories);
        return categoryList;
    }


    /**
     * 一级分类商品推荐
     *
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<CategoryProductDto> getCategoryProduct() {
        //查询顶级分类
        List<CategoryProductDto> catergoryProducts = categoryMapper.getCatergoryProducts();
        Map<Integer, List<CategoryProductDto>> categoryMap = catergoryProducts.stream().collect(Collectors.groupingBy(CategoryProductDto::getCategoryLevel));
        List<CategoryProductDto> topCategory = categoryMap.get(1);
        //查询每个销量前6的商品
        List<Product> productImgs = productMapper.getProductImgs();
        Map<Integer, List<Product>> productCategorizeMap = productImgs.stream().collect(Collectors.groupingBy(Product::getRootCategoryId));
        //对顶级层级根据productCategorizeMap key进行过滤优化商品匹配层级循环的次数
        Set<Integer> productCategorizeIds = productCategorizeMap.keySet();
        List<CategoryProductDto> CategoryProducts = topCategory.stream().filter(c -> productCategorizeIds.contains(c.getCategoryId())).collect(Collectors.toList());
        //商品匹配层级
        CategoryProducts.forEach(o -> {
            Integer categoryId = o.getCategoryId();
            List<Product> categoryProduct = productCategorizeMap.get(categoryId);
            List<Product> products = categoryProduct.stream().sorted((o1, o2) -> o2.getSoldNum() - o1.getSoldNum()).limit(6).collect(Collectors.toList());
//            List<Product> retrunProudct = new ArrayList<>();
//            Collections.sort(categoryProduct, Comparator.comparing(Product::getSoldNum).reversed());
//            retrunProudct.addAll(categoryProduct.subList(0, 6));
            o.setProducts(products);
        });
        List<CategoryProductDto> retrunCategoryProduct = CategoryProducts.stream().filter(c -> c.getProducts() != null).collect(Collectors.toList());
        return retrunCategoryProduct;
    }


    /**
     * version0 获取层级信息
     *
     * @param categories
     * @return
     */
    private List<Category> getCategories(List<Category> categories) {
        //获取所有类别层级
        List<Integer> levels = categories.stream().map(Category::getCategoryLevel).distinct().collect(Collectors.toList());
        //倒序层级从最低级到最高级
        Collections.sort(levels);
        //获取每个层级的list
        List<List<Category>> lists = new ArrayList<>();
        for (int i = levels.size() - 1; i >= 0; i--) {
            int index = i;
            lists.add(categories.stream().filter(o -> o.getCategoryLevel() == levels.get(index)).collect(Collectors.toList()));
        }
        //组装层级关系
        for (int i = 0; i < lists.size(); i++) {
            if (i + 1 == lists.size()) {
                break;
            }
            List<Category> categoryList = lists.get(i + 1);
            List<Category> categoryList1 = lists.get(i);
            for (Category category : categoryList) {
                List<Category> temp = new ArrayList<>();
                for (Category category1 : categoryList1) {
                    if (category.getCategoryId() == category1.getParentId()) {
                        temp.add(category1);
                        category.setCategories(temp);
                    }
                }
            }
        }
        //获取顶级
        List<Category> categoryList = lists.get(lists.size() - 1);
        return categoryList;
    }

    /**
     * version1 递归获取层级
     *
     * @param child
     * @param all
     * @return
     */
    public List<Category> categoriesRecursion(List<Category> child, List<Category> all) {

        return null;
    }

    /**
     * version2 获取层级
     * map数据结构
     *
     * @param list
     * @return
     */
    public List<Category> categoriesMap(List<Category> list) {

        Map<Integer, List<Category>> map = list.stream().collect(Collectors.groupingBy(Category::getParentId));

        List<Category> first = map.get(0);

        List<Category> returnList = mountLevel(first, map);

        return returnList;
    }

    /**
     * map数据结构递归
     *
     * @param first
     * @param map
     * @return
     */
    private List<Category> mountLevel(List<Category> first, Map<Integer, List<Category>> map) {
        for (Category category : first) {
            Integer categoryId = category.getCategoryId();
            List<Category> child = map.get(categoryId);
            if (child != null && child.size() > 0) {
                mountLevel(child, map);
                category.setCategories(child);
            } else {
                category.setCategories(new ArrayList<>());
            }

        }
        return first;
    }


}
